﻿using Google.Protobuf.WellKnownTypes;

public class NetHandler_BaseInfo : GameServerMessageHandler
{
    public const string Key = "UploadBaseInfo";
    //public static object baton = new object();

    public static NetHandler_BaseInfo NewHandler()
    {
        return new NetHandler_BaseInfo();
    }

    protected override ISerialize NewData() => new BaseInfoRequestData();

    public override void _Execute(TCPClient client, ISerialize _data)
    {
        BaseInfoRequestData requestData = _data as BaseInfoRequestData;

        GameDebug.Log($"用户{client.userID} 上传基本信息:{requestData?.userBaseInfoData}");

        UserServer user = Game.instance.GetUser(client.userID);

        ImageUrlResponseData response = new ImageUrlResponseData();

        if (user == null)
        {
            GameDebug.LogError($"找不到用户：{client.userID}");
            response.code = ErrorCode.UserNotFound;
        }
        else
        {
            if(requestData != null)
            {
                UserBaseInfoData baseInfo = requestData.userBaseInfoData;

                if (!Tex.IsNull(baseInfo.icon))
                {
                    int texId = 1;
                    Tex texData = requestData.userBaseInfoData.icon;
                    int setTextRet = TextureSaver.SaveUserTexture(client.userID, texId, texData.texWidth, texData.texHeight, texData.tex);

                    response.url = TextureSaver.GetUserTextureUrl(client.userID, texId);
                    GameDebug.Log($" 更新texture结果：setTextRet:{setTextRet}");
                }

                user.data.UpdateBaseInfo(baseInfo, response.url);

                int ret = users.UpdateBaseInfo(client.userID, baseInfo.gender, baseInfo.birthYear, baseInfo.edu,baseInfo.locationProvince,baseInfo.locationCity);

                GameDebug.Log($" 更新BaseInfo结果：{ret} gender:{user.data.userInfo.gender}");
                if(ret >= 0)
                    response.code = 0;
                else
                    response.code = -1;
            }
            else
            {
                GameDebug.LogError($"requestData == null _data:{_data!= null} type:{_data.GetType()}");
                response.code = -1;
            }
        }

        byte[] data = response.Write();
        this.SendResponse(client, Key, this.m_MessageReceived.seq, data);
    }
}
